package com.liu.common.handler;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Component
public class QuartzHandler {

    @Resource
    private Scheduler scheduler;

    @PostConstruct
    public void init() {
//        try {
//            scheduler.start();
//        } catch (SchedulerException e) {
//            throw new RuntimeException(e);
//        }
    }

    /**
     * 添加定时任务
     * @param interval interval
     * @param jobName jobName
     * @param jobGroupName jobGroupName
     * @param jobClass jobClass
     * @param jobDataMap jobDataMap
     * @throws SchedulerException 抛出异常
     */
    public void addTask(BigDecimal interval, String jobName, String jobGroupName, Class<? extends Job> jobClass, Map<String, Object> jobDataMap) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob()
                .ofType(jobClass)
                .withIdentity(jobName, jobGroupName) // 设置jobKey
                .storeDurably() // 设置任务持久化
                .build();
        jobDetail.getJobDataMap().put("jobParam", jobDataMap);
        SimpleTrigger trigger = TriggerBuilder.newTrigger().startNow()
                .startAt(new Date(System.currentTimeMillis() + interval.multiply(new BigDecimal("999")).intValue())) // 延迟1秒，防止任务立马执行
                .withIdentity(jobName, jobGroupName) // 设置triggerKey
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInMilliseconds(interval.multiply(new BigDecimal("1000")).intValue())
                        .repeatForever()
                )
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 删除定时任务
     * @param jobName jobName
     * @param jobGroupName jobGroupName
     * @throws SchedulerException 抛出异常
     */
    public void removeTask(String jobName, String jobGroupName) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
        // 停止触发器
        scheduler.pauseTrigger(triggerKey);
        // 移除触发器
        scheduler.unscheduleJob(triggerKey);
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        // 删除任务
        boolean isDeleted = scheduler.deleteJob(jobKey);
        if (isDeleted) {
            System.out.println("任务删除成功: " + jobName + "-" + jobGroupName);
        }
    }

    /**
     * 检查定时任务是否存在
     * @param jobName jobName
     * @param jobGroupName jobGroupName
     * @throws SchedulerException 抛出异常
     */
    public boolean checkTaskExist(String jobName, String jobGroupName) throws SchedulerException {
        // 使用JobKey，一直返回false（具体原因未知）
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
        return scheduler.checkExists(triggerKey);
    }

    /**
     * 获取任务参数
     * @param jobName jobName
     * @param jobGroupName jobGroupName
     * @return Map<String, Object>
     * @throws SchedulerException 抛出异常
     */
    public Map<String, Object> getJobParamMap(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        return (Map<String, Object>) jobDetail.getJobDataMap().get("jobParam");
    }

}
